<template>
  <div class="container">
    <el-card>
      <div class="top">
        <el-select v-model="evaluationType" placeholder="评教类型" size="large">
          <el-option v-for="item in evaluationTypes" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select v-model="quantile" placeholder="分位数" size="large">
          <el-option v-for="item in quantiles" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select v-model="delta" placeholder="delta值" size="large">
          <el-option v-for="d in deltas" :key="d" :label="d" :value="d" />
        </el-select>
        <el-button type="primary" round @click="analyse">开始分析</el-button>
      </div>
    </el-card>

    <div v-show="visible" class="main">
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column prop="info" label="名称" align="center" width="400" />
        <el-table-column label="分组（均值±标准差）" align="center">
          <el-table-column
            v-for="column in columns"
            :key="column.prop"
            :prop="column.prop"
            :label="column.label"
            align="center"
          />
        </el-table-column>
        <el-table-column prop="statistic" label="统计量" align="center" />
        <el-table-column prop="possibility" label="P值" align="center" />
      </el-table>
      <div class="text">
        <h3>说明<i class="el-icon-info" style="margin-left: 10px;" /></h3>
        项目分析（也称区分度分析）；其目的在于研究数据是否可以有效的区分出高低水平。<br>
        针对问卷的每项进行项目分析。如果p &lt; 0.05，则说明该项具有区分度，p越小则区分性越大。<br>
        可以删除区分度小的项以优化问卷。<br>
      </div>
      <div ref="chartRef" class="chart" />
    </div>

    <div
      v-show="!visible"
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      class="loading"
    />
  </div>
</template>

<script>
import { itemAnalysis } from '@/api/evaluation'
import { calcMean, calcStd } from '@/utils/calc'
import { Message } from 'element-ui'
import * as echarts from 'echarts'
export default {
  name: 'Item',
  data() {
    return {
      evaluationType: '1',
      evaluationTypes: [{
        label: '学生评教',
        value: '1'
      }, {
        label: '督导评教',
        value: '2'
      }],
      quantile: 0.27,
      quantiles: [{
        label: '27/73分位数',
        value: 0.27
      }, {
        label: '25/75分位数',
        value: 0.25
      }],
      delta: null,
      deltas: [0, 0.03, 0.05, 0.1, 0.15],
      tableData: [],
      columns: [],
      visible: false,
      loading: false,
      chart1: null
    }
  },
  mounted() {
    this.chart1 = echarts.init(this.$refs.chartRef)
  },
  methods: {
    analyse() {
      this.clear()
      this.visible = false // 隐藏
      this.loading = true // 加载
      if (this.evaluationType === null || this.quantile === null) {
        Message({
          message: '请选择参数',
          type: 'warning',
          duration: 2000
        })
        this.visible = false
        return
      }
      itemAnalysis(this.evaluationType, this.quantile, this.delta).then(res => {
        const data = res.data
        console.log('项目分析：', data)
        if (data === null) {
          Message({
            message: '没有数据',
            type: 'error',
            duration: 2000
          })
          return
        }
        // 构造组信息
        this.generateColumns(data[0].itemList)
        // 构造行信息
        const [xData, arr] = this.generateRow(data)
        // 绘制图表
        this.drawMeanChart(xData, arr)
        // 展示
        this.loading = false
        this.visible = true
      })
    },
    generateColumns(one) {
      for (let idx = 0; idx < one.length; idx++) {
        this.columns.push({ label: `${one[idx].info}（n=${one[idx].data.length}）`, prop: `group${idx}` })
      }
    },
    generateRow(data) {
      // 图表的数据
      const xData = []; const arr = []
      for (let idx = 0; idx < data.length; idx++) {
        const row = {}
        row.statistic = data[idx].statistic.toFixed(6)
        row.possibility = data[idx].possibility.toFixed(6)
        row.info = data[idx].info
        xData.push(`分析项${idx}`)
        const temp = []
        for (let index = 0; index < this.columns.length; index++) {
          const element = data[idx].itemList[index]
          const mean = calcMean(element.data); const std = calcStd(element.data, mean)
          row[`group${index}`] = `${mean} ± ${std}`
          temp.push(mean)
        }
        arr.push(temp)
        this.tableData.push(row)
      }
      console.log('tableData: ', this.tableData)
      return [xData, arr]
    },
    getData(arr) {
      const highGroup = []; const lowGroup = []
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < 2; j++) {
          if (j === 0) { highGroup.push(arr[i][j]) } else { lowGroup.push(arr[i][j]) }
        }
      }
      return [highGroup, lowGroup]
    },
    drawMeanChart(xData, arr) {
      const [highGroup, lowGroup] = this.getData(arr)

      const option = {
        title: {
          text: '分析结果'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['高分组', '低分组']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          data: xData
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '高分组',
            type: 'line',
            data: highGroup
          },
          {
            name: '低分组',
            type: 'line',
            data: lowGroup
          }
        ]
      }

      this.chart1.setOption(option)
    },
    clear() {
      this.columns = []
      this.tableData = []
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 30px;

  .top {
    display: flex;

    .el-select {
      margin-right: 30px;
    }
  }

  .main {
    margin-top: 30px;

    .chart {
      height: 600px;
      width: 800px;
      margin: 0 auto;
    }

    .text {
      margin: 30px 0 30px;
      background-color: #F3F9FE;
      padding: 10px;
    }
  }

  .loading {
    height: 70vh;
  }
}
</style>
